<template>
  <!--渠道-->
  <div v-if="editDialogVisible11">
    <!--按钮和输入框-->
    <el-form>
      <el-form-item>
        <el-form-item>
          <kt-button type="primary" @click="handleCodeDistribute" label="分发"></kt-button>
        </el-form-item>
      </el-form-item>

      <el-table :data="sourceDataList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="storeName" label="店铺"></el-table-column>
        <el-table-column prop="channelName" label="渠道"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button :size="size" type="primary" @click="handleCodeDistributeEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <!--渠道(分发至店铺弹窗)-->
    <el-dialog
      title="分发至店铺" width="80%" :visible.sync="distributionStoresDialog" :close-on-click-modal="false">
      <el-form :model="codeByShopDataForm" label-width="80px" :rules="codeByShopDataFormRules" ref="codeByShopDataForm"
               :inline="true" :size="size">
        <el-form-item label="店铺" prop="deptId">
          <el-select v-model="codeByShopDataForm.deptId" :disabled="distributionStoresSubmitVisible"
                     @change="selectTrigger">
            <el-option v-for="item in queryStoreList" :key="item.deptId" :label="item.storeName"
                       :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
          <el-input v-model="codeByShopDataForm.channelName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="运费模板" prop="freightTemplateId">
          <el-select v-model="codeByShopDataForm.freightTemplateId">
            <el-option v-for="item in queryFreightTemplate" :key="item.id" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-table :data="getProductParentList" border style="width: 100%">
        <el-table-column v-for="(item, index) in getProductParentAttrList" :key="item.attrId" :label="item.attrName">
          <template slot-scope="scope">
            {{scope.row.productPropertyResponseList[index].valueName}}
          </template>
        </el-table-column>
        <el-table-column label="商品编码" prop="code"></el-table-column>
        <el-table-column label="销售计量单位" prop="unitsName"></el-table-column>
        <el-table-column label="库存数量（件）">
          <template slot-scope="scope">
            <el-input v-model="scope.row.availableStock">
              <template slot="prepend">可售</template>
            </el-input>
            <el-input v-model="scope.row.blockStock" v-if="distributionStoresSubmitVisible" :disabled="true">
              <template slot="prepend">冻结</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="售价" prop="salePriceWithTax">
          <template slot-scope="scope">
            <el-input v-model="scope.row.salePriceWithTax" :disabled="scope.row.isAudit != 0"></el-input>
            <el-tooltip style="font-size: 20px;" effect="light" :enterable="false" placement="right"
                        v-if="scope.row.isAudit != 0">
              <div slot="content" style="min-width: 200px; min-height: 80px;">
                <p>价格正在审核中......</p>
                <p>发起人: {{scope.row.creator}}</p>
                <p>修改时间: {{scope.row.createTime}}</p>
              </div>
              <i class="el-icon-question"/>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="市场价" prop="marketPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.marketPrice"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="采购价" prop="purchasePriceWithTax">
          <template slot-scope="scope">
            <el-input v-model="scope.row.purchasePriceWithTax"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="团购价" prop="groupBuyingPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.groupBuyingPrice"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="distributionStoresDialog = false">{{$t("action.cancel") }}</el-button>
        <el-button v-if="!distributionStoresSubmitVisible" :disabled="getProductParentList.length < 1" :size="size"
                   type="primary" @click.native="distributionStoresSubmit" :loading="editLoading">{{ $t("action.submit")
          }}
        </el-button>
        <el-button v-if="distributionStoresSubmitVisible" :disabled="getProductParentList.length < 1" :size="size"
                   type="primary" @click.native="distributionStoresSubmit1" :loading="editLoading">{{
          $t("action.update") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CyTable from "@/views/Core/CyTable";
  import KtButton from "@/views/Core/KtButton";
  import {format, formatDate} from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";

  export default {
    components: {
      KtButton,
      CyTable,
      TableColumnFilterDialog
    },
    data() {
      return {
        loading: true,
        size: "small",
        editDialogVisible11: false,
        editLoading: false,
        productId: 0,
        sourceDataList: [],
        queryStoreList: [],
        queryFreightTemplate: [],
        channelList: [
          {id: 'B2B', name: 'B2B'},
          {id: 'BBC', name: 'BBC'},
          {id: 'O&O', name: 'O&O'},
          {id: 'B2C', name: 'B2C'},
          {id: '京东', name: '京东'},
          {id: '天猫', name: '天猫'}
        ],
        distributionStoresDialog: false, // 渠道分发、编辑弹出框
        distributionStoresSubmitVisible: false, // 渠道列表编辑提交按钮
        codeByShopDataForm: {
          deptId: '',
          storeName: '',
          channelCode: '',
          channelName: '',
          freightTemplateId: '',
          productId: ''
        },
        codeByShopDataFormRules: {
          storeId: [{required: true, message: "请输入店铺", trigger: "change"}],
          channelCode: [{required: true, message: "请输入渠道", trigger: "change"}],
          freightTemplateId: [{required: true, message: "请输入运费模板", trigger: 'change'}]
        },
        getProductParentList: [],
        getProductParentAttrList: [],
        status: 0,
      };
    },
    methods: {
      init(param) {
        this.editDialogVisible11 = param.flag;
        this.productId = param.productId;
        this.status = param.status;
        if (param.flag) {
          this.queryProductSource()
          this.queryStoreListData()
          this.queryFreightTemplateData();
        }
      },
      // 店铺
      queryStoreListData() {
        let this_ = this;
        let param = {};
        this.utils.request.queryStoreList(param, function (data) {
          if (data.data != null) {
            this_.queryStoreList = data.data
          }
        });
      },
      // 运费模板下拉框
      queryFreightTemplateData() {
        let this_ = this;
        this.utils.request.queryFreightTemplate({}, function (data) {
          if (data.data) {
            this_.queryFreightTemplate = data.data;
          }
        });
      },
      // 渠道列表查询
      queryProductSource() {
        let this_ = this;
        let param = {};
        param.productId = this.productId;
        this.utils.request.queryProductSource(param, function (data) {
          this_.loading = false;
          if (data.data != null) {
            this_.sourceDataList = data.data;
          }
        });
      },
      //  分发和:编辑列表查询 dataType: 1-运营商品;2-商家商品;3-店铺商品
      handleFindProductParent(dataType, proId) {
        
        let this_ = this;
        let params = {};
        if (proId == null) {
          params.productId = this_.productId;
        } else {
          params.productId = proId;
        }
        params.dataType = dataType;
        this.utils.request.getProductParent(params, function (res) {
          this_.getProductParentList = res.data;
          $.each(res.data, function (index, val) {
            if (index === 0) {
              this_.getProductParentAttrList = res.data[index].productPropertyResponseList;
              return;
            }
          })
        });
      },
      // 渠道分发店铺弹窗
      handleCodeDistribute() {
        if (this.status != 2) {
          this.$message({message: "商品审核通过后才可以分发到店铺", type: "warning"});
          return;
        }
        let this_ = this;
        this_.codeByShopDataForm = {
          storeName: '',
          channelCode: '',
          channelName: '',
          freightTemplateId: '',
          productId: '',
          deptId: ""
        };
        if (this_.$refs['codeByShopDataForm'] !== undefined) {
          this_.$refs['codeByShopDataForm'].resetFields();
        }
        this_.distributionStoresSubmitVisible = false;
        this_.distributionStoresDialog = true;
        this_.handleFindProductParent(2, null);
      },
      // 渠道分发店铺提交
      distributionStoresSubmit() {
        let this_ = this;
        this.$refs.codeByShopDataForm.validate(valid => {
          if (valid) {
            let params = {};
            let productDistributeStoreParentRequests = [];
            params.productId = this_.productId;
            params.dataType = 3;
            params.deptId = this_.codeByShopDataForm.deptId;
            params.freightTemplateId = this_.codeByShopDataForm.freightTemplateId;
            params.storeName = this_.codeByShopDataForm.storeName;
            params.channelCode = this_.codeByShopDataForm.channelCode;
            params.channelName = this_.codeByShopDataForm.channelName;
            $.each(this_.getProductParentList, function (index, val) {
              if (val != null && val != '') {
                let list = {};
                list.productId = val.id;
                list.salePriceWithTax = val.salePriceWithTax;
                list.groupBuyingPrice = val.groupBuyingPrice;
                list.purchasePriceWithTax = val.purchasePriceWithTax;
                list.marketPrice = val.marketPrice;
                list.unitsName = val.unitsName;
                list.availableStock = val.availableStock;
                productDistributeStoreParentRequests.push(list);
              }
            });
            params.productDistributeStoreParentRequests = productDistributeStoreParentRequests;
            this.utils.request.saveProductDistributeStore(params, function (res) {
              if (res.code == "0000") {
                this_.queryProductSource();
                this_.distributionStoresDialog = false;
                this_.$message({message: "操作成功", type: "success"});
              } else {
                this_.$message({message: "操作失败, " + res.msg, type: "error"});
              }
            });
          }
        });
      },
      // 渠道列表编辑显示
      handleCodeDistributeEdit(data) {
        this.codeByShopDataForm = {
          deptId: Number(data.deptId),
          channelCode: data.channelCode,
          channelName: data.channelName,
          freightTemplateId: data.freightTemplateId.toString(),
        };
        let this_ = this;
        this_.handleFindProductParent(3, data.id);
        this_.distributionStoresSubmitVisible = true;
        this_.distributionStoresDialog = true;
      },
      selectTrigger(val) {
        let obj = {};
        obj = this.queryStoreList.find(item => { // 这里的sourceDataList就是上面遍历的数据源
          return Number(item.deptId) === Number(val); // 筛选出匹配数据
        });
        if (obj) {
          this.codeByShopDataForm.storeName = obj.storeName;
          this.codeByShopDataForm.channelName = obj.channelName;
        }
      },
      // 渠道列表编辑修改
      distributionStoresSubmit1() {
        this.$refs.codeByShopDataForm.validate(valid => {
          if (valid) {
            let this_ = this;
            let params = {};
            let productDistributeStoreParentRequests = [];
            params.dataType = 3;
            params.productId = this_.codeByShopDataForm.productId;
            params.freightTemplateId = this_.codeByShopDataForm.freightTemplateId;
            $.each(this_.getProductParentList, function (index, val) {
              if (val != null && val != '') {
                let list = {};
                list.productId = val.id;
                list.salePriceWithTax = val.salePriceWithTax;
                list.groupBuyingPrice = val.groupBuyingPrice;
                list.purchasePriceWithTax = val.purchasePriceWithTax;
                list.marketPrice = val.marketPrice;
                list.canSale = val.canSale;
                list.isAudit = val.isAudit
                list.unitsName = val.unitsName;
                list.availableStock = val.availableStock;
                productDistributeStoreParentRequests.push(list);
              }
            });
            params.productDistributeStoreParentRequests = productDistributeStoreParentRequests;
            this.utils.request.updateProductDistributeStore(params, function (res) {
              if (res.code == "0000") {
                this_.queryProductSource();
                this_.distributionStoresDialog = false;
                this_.$message({message: "操作成功", type: "success"});
              } else {
                this_.$message({message: "操作失败, " + res.msg, type: "error"});
              }
            });
          }
        });
      },
    }
  };
</script>

<style scoped>

</style>
